//
//  LDSoundController.m
//  cliptest
//
//  Created by James Tong on 18/06/2010.
//  Copyright 2010 __MyCompanyName__. All rights reserved.
//

#import "LDSoundController.h"


@implementation LDSoundController

+ (LDSoundController *) sharedInstance {
	static LDSoundController *sharedInstance;
	
	@synchronized(self) {
		if (!sharedInstance)
			sharedInstance = [[LDSoundController alloc] init];
		return sharedInstance;
	}
}

- (id) init {
	
	if (self = [super init]) {
		InitAudioSession(kAudioSessionCategory_AmbientSound, NULL, NULL);
		[self initOpenAL];
	}
	return self;
	
} // init

- (void) initOpenAL {

	ALsizei	data_size;
	ALenum	al_format;
	ALsizei sample_rate;
	
	NSURL* fileURL;
		
	// NULL是iphone的default device，由系統決定（例如耳筒），一般情況下都應該使用default
	openALDevice = alcOpenDevice(NULL);
	openALContext	= alcCreateContext(openALDevice, 0);
	alcMakeContextCurrent(openALContext);
	

//	alGenSources(1, &outputSource2);
	
	// 給第一條source一個buffer
	alGenBuffers(2, outputBuffer);
//	alGenBuffers(1, &click01OutputBuffer);

	// 載入sound file，wav格式
	fileURL = [[NSURL alloc] initFileURLWithPath:[[NSBundle mainBundle] 
					pathForResource:@"laser1" 
					ofType:@"wav"]];
	laserPcmData = MyGetOpenALAudioDataAll((CFURLRef)fileURL, &data_size, &al_format, &sample_rate);
	[fileURL release];
	
	alBufferData(outputBuffer[0], al_format, laserPcmData, data_size, sample_rate);
	free(laserPcmData);
	laserPcmData = NULL;
	
	fileURL = [[NSURL alloc] initFileURLWithPath:[[NSBundle mainBundle] 
					pathForResource:@"click01" 
					ofType:@"wav"]];
	click01PcmData = MyGetOpenALAudioDataAll((CFURLRef)fileURL, &data_size, &al_format, &sample_rate);
	[fileURL release];
	
	// 將剛載入的音頻資訊放入buffer
	
	
	alBufferData(outputBuffer[1], al_format, click01PcmData, data_size, sample_rate);
	free(click01PcmData);
	click01PcmData = NULL;
	
	// 告訴OpenAL要建立多少條同時發聲的source
	alGenSources(2, outputSource);
	
	// alSourcei是設定source用，在這裡是將buffer指給source
	alSourcei(outputSource[0], AL_BUFFER, outputBuffer[0]);
	alSourcei(outputSource[1], AL_BUFFER, outputBuffer[1]);
} // initOpenAL

- (void) playLaser
{
	alSourcePlay(outputSource[0]);
}

- (void) playClick01 {
	alSourcePlay(outputSource[1]);
}

- (void) dealloc {

	// shutdown OpenAL	
	alDeleteSources(2, outputSource);
//	alDeleteSources(1, outputSource[1]);
	alDeleteBuffers(2, outputBuffer);
//	alDeleteBuffers(1, outputBuffer[1]);
	alcMakeContextCurrent(NULL);
	if(openALContext) {
		alcDestroyContext(openALContext);
		openALContext = NULL;
	}
	if(openALDevice) {
		alcCloseDevice(openALDevice);
		openALDevice = NULL;
	}
	if(laserPcmData) {
		free(laserPcmData);
		laserPcmData = NULL;
	}
	if (click01PcmData) {
		free(click01PcmData);
		click01PcmData = NULL;
	}

	[super dealloc];
}

@end
